package com.agger.harmonyosthemeseditor.abilities.slices;

import com.agger.harmonyosthemeseditor.ResourceTable;
import com.agger.harmonyosthemeseditor.ThemesEditorAbility;
import com.agger.harmonyosthemeseditor.intelligent.DatabaseManager;
import com.agger.harmonyosthemeseditor.intelligent.FileManager;
import com.agger.harmonyosthemeseditor.intelligent.GeneralUtil;
import com.agger.harmonyosthemeseditor.userinterface.RequestDialog;
import com.agger.harmonyosthemeseditor.userinterface.ResourceTool;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.text.RichText;
import ohos.agp.text.RichTextBuilder;
import ohos.agp.text.TextForm;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.bundle.AbilityInfo;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.ResourceManager;
import ohos.miscservices.wallpaper.WallpaperController;
import ohos.os.ProcessManager;

import java.io.File;
import java.io.FileInputStream;

public class AboutSlice extends AbilitySlice
{
    RequestDialog requestDialog = null;
    String Dialog_Text = "停止服务后将无法使用本应用，并会退出应用。确定停止服务？";
    String Dialog_Button_Cancel = "取消";
    String Dialog_Button_Accent = "停止";
    private int RichTextCode = -1;
    public static AboutSlice Instance;
    public boolean isOnline = false;

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation)
    {
        super.onOrientationChanged(displayOrientation);
        ReDialog();
    }
    public void ReDialog()
    {
        try
        {
            if(!requestDialog.isDestroyed)
            {
                if(!requestDialog.isShowing())
                {
                    requestDialog.destory();
                    requestDialog = null;
                    System.gc();
                }
                else
                {
                    requestDialog.destory();
                    requestDialog = null;
                    System.gc();
                    StopService();
                }
            }
        }catch (Exception ex){}
    }

    @Override
    public void onStart(Intent intent)
    {
        Instance = this;
        requestDialog = null;
        isOnline = true;
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_about);
        //设定状态栏沉浸
        this.getWindow().setStatusBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_normal,0xF7EDD8));
        this.getWindow().setNavigationBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_navigationbar_normal,0xF7EDD8));
        int CurrentColorMode = getColorMode();
        if(CurrentColorMode == 0) this.getWindow().setStatusBarVisibility(0);
        else if(CurrentColorMode == 1) this.getWindow().setStatusBarVisibility(2052);
        ThemesEditorAbility.Instance.eventRunner = EventRunner.current();
        GeneralUtil.setWindowToMaxRefreshRate(getWindow());
        ResourceManager resManager = getResourceManager();
        try
        {
            Dialog_Text = resManager.getElement(ResourceTable.String_StopServiceDialog_Text).getString();
            Dialog_Button_Cancel = resManager.getElement(ResourceTable.String_buttoncancel).getString();
            Dialog_Button_Accent = resManager.getElement(ResourceTable.String_StopServiceDialog_AccentButton).getString();
        }catch (Exception e){}
        DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes();
        Component AboutContent = findComponentById(ResourceTable.Id_AboutContent);
        Component AboutFiled = findComponentById(ResourceTable.Id_AboutFiled);
        AboutContent.setLayoutRefreshedListener(c->
        {
            int aHeight = AboutContent.getHeight();
            int minHeight = (int)(368f*displayAttributes.scalDensity+0.5f);
            AboutFiled.setMinHeight(aHeight>minHeight?aHeight:minHeight);
        });
        Text VersionText = (Text)findComponentById(ResourceTable.Id_AboutSlice_VersionText);
        VersionText.setText(ResourceTool.getString(this,ResourceTable.String_AboutScene_VersionText,"版本")+" "+ GeneralUtil.VersionCode);
        findComponentById(ResourceTable.Id_AboutSlice_OpenSourceText).setClickedListener(c->onClickNewScene("OpenSource"));
        Text text = (Text)findComponentById(ResourceTable.Id_AboutSlice_BotomRichText);
        String BottomText = "主题协作器用户协议$和$关于主题协作器与隐私的声明";
        try{BottomText = getResourceManager().getElement(ResourceTable.String_AboutScene_BottomText).getString();}catch (Exception ex){}
        String[] BottomTexts = BottomText.split("\\$");
        int textSize = (int)(12f*displayAttributes.scalDensity*getResourceManager().getConfiguration().fontRatio);
        int textColor = ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_text_secondary,0);
        int textColor_accent = ResourceTool.getColor(getContext(),ResourceTable.Color_dawnlighti_accent,0);
        RichTextBuilder builder = new RichTextBuilder();
        builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor_accent));
        builder.addText(BottomTexts[0]);
        builder.revertForm();
        builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor));
        builder.addText(BottomTexts[1]);
        builder.revertForm();
        builder.mergeForm(new TextForm().setTextSize(textSize).setTextColor(textColor_accent));
        builder.addText(BottomTexts[2]);
        RichText richTextContent = builder.build();
        text.setRichText(richTextContent);
        RichTextCode = -1;
        richTextContent.addTouchEventListener((component, touchEvent) ->
        {
            if(touchEvent.getAction() == 1) RichTextCode = 0;
            return true;
        },0,BottomTexts[0].length()-1);
        richTextContent.addTouchEventListener((component, touchEvent) ->
        {
            if(touchEvent.getAction() == 1) RichTextCode = 1;
            return true;
        },BottomTexts[0].length()+BottomTexts[1].length(),BottomText.length()-3);
        text.setClickedListener(c->
        {
            if(RichTextCode == 0)
            {
                RichTextCode = -1;
                onClickNewScene("UserAgreement");
            }else if(RichTextCode == 1)
            {
                RichTextCode = -1;
                onClickNewScene("PrivacyStatement");

            }
        });
        /*if(ThemesEditorAbility.API_Version_Code<7)
        {

        }else
        {
            RichText richTextContent = new RichText(BottomText.replaceAll("\\$",""));
            richTextContent.setRichStyle(new ClickRichStyle(component ->
            {
                onClickNewScene("UserAgreement");
            }),0,BottomTexts[0].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);

            richTextContent.setRichStyle(new ClickRichStyle(component ->
            {
                onClickNewScene("PrivacyStatement");
            }),BottomTexts[0].length()+BottomTexts[1].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new FontSizeRichStyle(textSize, Text.TextSizeType.PX),0,BottomTexts[0].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new FontSizeRichStyle(textSize, Text.TextSizeType.PX),BottomTexts[0].length(),BottomTexts[0].length()+BottomTexts[1].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new FontSizeRichStyle(textSize, Text.TextSizeType.PX),BottomTexts[0].length()+BottomTexts[1].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new ForegroundColorRichStyle(new Color(textColor_accent)),0,BottomTexts[0].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new ForegroundColorRichStyle(new Color(textColor)),BottomTexts[0].length(),BottomTexts[0].length()+BottomTexts[1].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            richTextContent.setRichStyle(new ForegroundColorRichStyle(new Color(textColor_accent)),BottomTexts[0].length()+BottomTexts[1].length(),BottomTexts[0].length()+BottomTexts[1].length()+BottomTexts[2].length(), RangedRichStyle.Flag.INCLUDE_START_AND_END);
            text.setRichText(richTextContent);
        }*/
        findComponentById(ResourceTable.Id_AboutScene_Icon).setAlpha((ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_color_mode,-1)==-16777216)?0.6f:1f);
        findComponentById(ResourceTable.Id_AboutSlice_ButtonStop).setClickedListener(c->
        {
            if(requestDialog == null)
                StopService();
            else
            {
                if(!requestDialog.isDestroyed)
                {
                    requestDialog.destory();
                    requestDialog = null;
                    System.gc();
                    StopService();
                }
                else
                {
                    requestDialog = null;
                    System.gc();
                    StopService();
                }
            }
        });
        Component AboutBox_DataSharing = findComponentById(ResourceTable.Id_AboutBox_DataSharing);
        Component AboutBox_SdkList = findComponentById(ResourceTable.Id_AboutBox_SdkList);
        Component AboutBox_InfoCollected = findComponentById(ResourceTable.Id_AboutBox_InfoCollected);
        AboutBox_DataSharing.setClickedListener(c->onClickNewScene("DataSharingList"));
        AboutBox_SdkList.setClickedListener(c->onClickNewScene("SdkList"));
        AboutBox_InfoCollected.setClickedListener(c->onClickNewScene("InfoCollectedList"));
        Component Actionbar_Back_Item_Pressed = findComponentById(ResourceTable.Id_actionBar_Back_Pressed_Item);
        Component Actionbar_Back_Button = findComponentById(ResourceTable.Id_actionBar_Back);
        Actionbar_Back_Button.setClickedListener
                (c -> {
                    onBackPressed();
                });
        Actionbar_Back_Button.setComponentStateChangedListener((c,i) ->
        {
            if(i == 18432)
                Actionbar_Back_Item_Pressed.setVisibility(Component.VISIBLE);
            else
                Actionbar_Back_Item_Pressed.setVisibility(Component.INVISIBLE);
        });
        DatabaseManager.Init(this);
        String LastSceneName = DatabaseManager.getString("AboutSlice_LastSceneName","None");
        if(!LastSceneName.equals("None"))
        {
            onClickNewScene(LastSceneName);
        }
        System.gc();
    }

    private void onClickNewScene(String SceneName)
    {
        try
        {
            Class<AbilitySlice> c = (Class<AbilitySlice>) Class.forName("com.agger.harmonyosthemeseditor.abilities.slices."+SceneName+"Slice");
            AbilitySlice abilitySlice = c.newInstance();
            present(abilitySlice,getAbility().getIntent());
            DatabaseManager.Init(this);
            DatabaseManager.setString("AboutSlice_LastSceneName",SceneName);
        }catch (Exception ex){}
    }

    private void StopService()
    {
        requestDialog = new RequestDialog(this);
        requestDialog
                .setText(Dialog_Text)
                .setEmptyButton(Dialog_Button_Cancel)
                .setAccentButton(Dialog_Button_Accent,c->
                {
                    if(ThemesEditorAbility.EnableWallpaperFadeEffect)
                    {
                        try
                        {
                            WallpaperController wallpaperController = WallpaperController.getInstance(this);
                            if(new File(getFilesDir()+"/user_wallpaper.jpg").exists())
                                wallpaperController.setWallpaper(new FileInputStream(getFilesDir()+"/user_wallpaper.jpg"),WallpaperController.WALLPAPER_SYSTEM);
                        }catch(Exception e){e.printStackTrace();}
                    }
                    FileManager.deleteDirectory("mnt/mdfs/account_trust/merge_view/data/com.agger.harmonyosthemeseditor",false,false);
                    getAbilityManager().clearUpApplicationData();
                    ProcessManager.kill(ProcessManager.getPid());
                },true)
                .setOutsideTouchClosable(false)
                .setMovable(false)
                .show();
    }

    @Override
    public void onBackPressed()
    {
        isOnline = false;
        DatabaseManager.Init(this);
        DatabaseManager.setString("LastAbilityName","None");
        try{getWindow().setNavigationBarColor(ResourceTool.getColor(this, ResourceTable.Color_dawnlighti_navigationbar_bottom, 0xF5F1E6));}catch (Exception ex){}
        Instance = null;
        ThemesEditorAbility.isMainSceneSlice = true;
        requestDialog = null;
        System.gc();
        if(ThemesEditorAbility.LayoutChanged)
        {
            ThemesEditorAbility.LayoutChanged = false;
            try{MainSceneSlice.Instance.restart();}catch (Exception ex){}
        }
        super.onBackPressed();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}